package com.gt.framework.security.wxauth;

import com.gt.common.core.domain.entity.SysUser;
import com.gt.common.core.domain.model.LoginUser;
import com.gt.common.utils.spring.SpringUtils;
import com.gt.framework.web.service.SysPermissionService;
import com.gt.system.service.ISysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.HashSet;
import java.util.Set;

/**
 * @author fishness
 * 2023-07-26
 */
public class SsoAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        SysUser user = SpringUtils.getBean(ISysUserService.class).selectUserByUserName(username);
        return new UsernamePasswordAuthenticationToken(createLoginUser(user),authentication);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(),user.getDeptId(),user, SpringUtils.getBean(SysPermissionService.class).getMenuPermission(user));
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(SsoAuthenticationToken.class);
    }
}
